﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DFGK.Service
{
    public class DictItemService : BaseService, IDictItemService
    {
        private readonly IDictItemRepository _dictitemrepository;
        private readonly IDictTypeRepository _dicttyperepository;
        private readonly IUnitOfWork _unitOfWork;
        public DictItemService(IMapper mapper, IDictItemRepository _dictitemrepository, IDictTypeRepository _dicttyperepository, IUnitOfWork _unitOfWork) : base(mapper)
        {
            this._dictitemrepository = _dictitemrepository;
            this._dicttyperepository = _dicttyperepository;
            this._unitOfWork = _unitOfWork;
        }
        /// <summary>
        /// 添加字典项
        /// </summary>
        /// <param name="dictItem"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool AddDictItem(DictItem dictItem, out string message)
        {
            string code = "DictItem";
            var aobj = _dictitemrepository.GetEntityWhereAll(x => x.ItemCode.Contains(code)).OrderByDescending(x => x.CreateDate).FirstOrDefault();
            if (aobj != null)
            {
                string pattern = @"\d+";
                MatchCollection matches = Regex.Matches(aobj.ItemCode, pattern);
                string value = matches[matches.Count - 1].Value;
                int values = Convert.ToInt32(value);
                values++;
                dictItem.ItemCode = code + values.ToString("D4");
            }
            else
            {
                int i = 1;
                dictItem.ItemCode = code + i.ToString("D4");
            }
            message = "";
            
            //查询所属字典类型
            var dictypeobj = _dicttyperepository.QueryEntityById(dictItem.TypeId);
            if (dictypeobj != null)
            {
                dictItem.TypeCode = dictypeobj.TypeCode;
            }
            _dictitemrepository.AddEntity(dictItem);
            return _unitOfWork.SaveChangesEntity();
        }

        /// <summary>
        /// 删除字典项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelDictItem(long id)
        {
            var dic = _dictitemrepository.QueryEntityById(id);
            if (dic !=null)
            {
               _dictitemrepository.DelEntity(dic);
                return _unitOfWork.SaveChangesEntity();
            }
            return false;
        }

        /// <summary>
        /// 字典树显示
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="typeId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<DictItem> GetAllDictItemList(string? keyword, long typeId, int pageIndex, int pageSize, out int totalCount)
        {
            var dicList = _dictitemrepository.GetEntityWhereAll(c => c.TypeId == typeId).AsQueryable();
            if (!string.IsNullOrEmpty(keyword))
            {
                dicList = dicList.Where(c => c.ItemName.Contains(keyword));
            }
            var list = _dictitemrepository.GetEntityAlls(dicList, pageIndex, pageSize, out totalCount, x => x.CreateDate, false);
            return list.ToList();
        }

        /// <summary>
        /// 根据字典类型id查询字典项
        /// </summary>
        /// <param name="dictypeId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<DictItem> GetDictItemByDicTypeId(int dictypeId, int pageIndex, int pageSize, out int totalCount)
        {
            var dicList = _dictitemrepository.GetEntityWhereAll(c => c.TypeId == dictypeId);
            var list = _dictitemrepository.GetEntityAlls(dicList, pageIndex, pageSize, out totalCount, x => x.CreateDate, false);
            return list.ToList();
        }

        /// <summary>
        /// 根据主键获取对象信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public DictItem? GetDictItemById(long id)
        {
            return _dictitemrepository.QueryEntityById(id);
        }

        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<DictItem> GetDictItems()
        {
            var list = _dictitemrepository.GetEntityAlls();
            return list.ToList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="itemName"></param>
        /// <param name="typeId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<DictItemDto> GetDictItemTreeByitemName(string? itemName, int typeId)
        {
            var res = _dictitemrepository.GetEntityWhereAll(a => a.TypeId == typeId).AsQueryable();
            if (!string.IsNullOrEmpty(itemName))
            {
                res = res.Where(x => x.ItemName.Contains(itemName));
            }
            return BuildTree(res, 0);
        }
        private static List<DictItemDto> BuildTree(IQueryable<DictItem> items, long parentId)
        {
            try
            {
                return items.ToList().Where(x => x.ParentId == parentId).Select(x => new DictItemDto
                {
                    Id = x.Id,
                    TypeId = x.TypeId,
                    ItemName = x.ItemName,
                    ParentId = x.ParentId,
                    ItemCode = x.ItemCode,
                    CreateDate = x.CreateDate,
                    CreateUserId = x.CreateUserId,
                    CreateUserName = x.CreateUserName,
                    Children = BuildTree(items, x.Id)
                }).ToList();
            }
            catch (Exception)
            {

                throw;
            }

        }
        public List<MenuDto> GetMenuLists(int pageIndex, int pageSize, out int totalCount, int typeid, string name)
        {
            var dicitem =_dictitemrepository.GetEntityWhereAll(c => c.TypeId == typeid).AsQueryable();
            if (!string.IsNullOrEmpty(name))
            {
                dicitem = dicitem.Where(x => x.ItemName.Contains(name));
            }
            if (dicitem.Any())
            {
                dicitem = dicitem.OrderBy(x => x.ParentId);
                var mmlist = dicitem.FirstOrDefault();
                var list = GetMenuLists(dicitem.ToList(), mmlist.ParentId.GetValueOrDefault());
                totalCount = list.Count;
                list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                return list;
            }
            var list2 = GetMenuLists(dicitem.ToList(), 0);
            totalCount = list2.Count;
            list2 = list2.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return list2;
        }
        public static List<MenuDto> GetMenuLists(List<DictItem> list, long pid)
        {
            return list.Where(x => x.ParentId == pid).Select(x => new MenuDto
            {
                id = x.Id,
                ParentId = x.ParentId,
                Meta = new MetaDto
                {
                    MenuName = x.ItemName,
                    MenuIcon = x.ItemCode,
                },
                DisplayOrder = x.DisplayOrder,
                children = GetMenuLists(list, x.Id)
            }).OrderBy(x => x.DisplayOrder).ToList();
        }
        public bool UpdDictItem(DictItem dictItem, out string message)
        {
            message = "";
            var dictitemobj = _dictitemrepository.QueryIsEntityWhere(x => x.Id != dictItem.Id && x.ItemCode == dictItem.ItemCode);
            if (dictitemobj != null)
            {
                message = "编码已存在！";
                return false;
            }
            var dictypeobj = _dicttyperepository.QueryEntityById(dictItem.TypeId);
            if (dictypeobj != null)
            {
                dictItem.TypeCode = dictypeobj.TypeCode;
            }
            _dictitemrepository.UpdEntity(dictItem);
            return _unitOfWork.SaveChangesEntity();
        }
    }
}
